﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ANZ_AIM_GUI.Utils;
using ANZ_AIM_BLL;
using ANZ_AIM_BLL.Model;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.IO;
using log4net;
namespace ANZ_AIM_GUI
{
    public partial class frmCandidateApproved : Form
    {
        //log4net
        private static readonly ILog logger = LogManager.GetLogger(typeof(frmCandidateApproved));

        protected AppParam appParam = AppParam.Instance;

        bool isApprove = false;
        public frmCandidateApproved(bool isApprove)
        {
            try
            {
                InitializeComponent();
                this.isApprove = isApprove;
                // LoadData();
                buttonX2.Text = "APPROVED" + Environment.NewLine + "20";
                buttonX3.Text = "PENDING" + Environment.NewLine + "15";
                buttonX4.Text = "READY TO APPROVE" + Environment.NewLine + "5";

                dtFromDate.Value = DateTime.Now;
                dtToDate.Value = DateTime.Now;

                // appParam.Role = User.ROLE_VERIFIER;

                if (!isApprove)
                {
                    this.Text = "CANDIDATE VERIFY";
                    groupBox1.Text = "Need To Verify";
                    groupBox3.Visible = false;
                    groupBox4.Visible = false;
                    tabControl1.Tabs[0].Visible = false;
                    this.Size = new Size(900, 315);
                }
                else
                {
                    this.Text = "CANDIDATE APPROVE";
                    groupBox3.Visible = true;
                    groupBox4.Visible = true;
                    tabControl1.Tabs[0].Visible = true;
                }

                InitData();
            }
            catch (Exception ex) { throw ex; }
        }

        private void InitData()
        {
            try
            {
                string status = "";
                if (!isApprove)
                {
                    status = Constant.NEED_TO_VERIFY;
                }
                else
                {
                    status = Constant.NEED_TO_APPROVE;
                }


                BatchFileUploadBLL batchFileUploadBll = new BatchFileUploadBLL();
                DataTable dtResult = batchFileUploadBll.GetBatchFileByStatus(status);
                LoadData(dtResult);
                loadDataApproved();
                loadDataPending();
            }
            catch (Exception ex) { throw ex; }
        }

        private void LoadData(DataTable dtData)
        {
            try
            {
                dgvData.DataSource = null;
                dgvData.Columns.Clear();
                dgvData.DataSource = dtData;
                dgvData.Columns[0].HeaderText = "Batch File";
                dgvData.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvData.Columns[1].HeaderText = "File Name";
                dgvData.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dgvData.Columns[2].HeaderText = "Total Record";
                dgvData.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                dgvData.Columns[3].HeaderText = "Uploaded Date";
                dgvData.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvData.Columns[4].Visible = false;
                dgvData.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                //add column action
                DataGridViewLinkColumn colAction = new DataGridViewLinkColumn();
                colAction.HeaderText = "Status";
                colAction.Name = "Status";
                if (!isApprove)
                {
                    colAction.Text = "Verify";
                }
                else
                {
                    colAction.Text = "Approve";
                }
                colAction.Width = 70;
                colAction.UseColumnTextForLinkValue = true;
                dgvData.Columns.Insert(5, colAction);
                this.dgvData.Sort(this.dgvData.Columns[3], ListSortDirection.Descending);
            }
            catch (Exception ex) { throw ex; }
        }

        private void dgvData_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                DataGridView dgv = sender as DataGridView;
                if (dgv.Columns[e.ColumnIndex].Name == "Status")
                {
                    string batchFileID = dgvData.Rows[e.RowIndex].Cells["BatchFileID"].Value.ToString();

                    if (!isApprove)
                    {
                        frmCandidateVerifyStatus frm = new frmCandidateVerifyStatus(batchFileID);
                        DialogResult result = frm.ShowDialog(this);
                        if (result == DialogResult.OK)
                        {
                            InitData();
                        }
                    }
                    else
                    {
                        frmCandidateApproveStatus frm = new frmCandidateApproveStatus(batchFileID);
                        DialogResult result = frm.ShowDialog(this);
                        if (result == DialogResult.OK)
                        {
                            InitData();
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                string fromDate = dtFromDate.Value.ToShortDateString();
                string toDate = dtToDate.Value.AddDays(1).ToShortDateString();

                string status = "";
                if (!isApprove)
                {
                    status = Constant.NEED_TO_VERIFY;
                }
                else
                {
                    status = Constant.NEED_TO_APPROVE;
                }


                string batchFile = txtBatchFile.Text.Trim();

                BatchFileUploadBLL batchFileUploadBll = new BatchFileUploadBLL();
                DataTable dt = batchFileUploadBll.Search(status, batchFile, fromDate, toDate);

                LoadData(dt);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void dgvData_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                int selectedRowCount = dgvData.Rows.GetRowCount(DataGridViewElementStates.Selected);
                if (selectedRowCount > 0)
                {
                    DataRow dr = ((DataRowView)dgvData.SelectedRows[0].DataBoundItem).Row;
                    frmDataUpload frmDateUpload = new frmDataUpload(dr[0].ToString());
                    frmDateUpload.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void loadDataApproved()
        {
            try
            {
                BatchFileUploadBLL batchFileUploadBll = new BatchFileUploadBLL();
                DataTable dtResult = batchFileUploadBll.GetBatchFileByStatus(Constant.APPROVED);

                dgvDataApproved.DataSource = null;
                dgvDataApproved.Columns.Clear();
                dgvDataApproved.DataSource = dtResult;
                this.dgvDataApproved.Sort(this.dgvDataApproved.Columns[3], ListSortDirection.Descending);
                dgvDataApproved.Columns[0].HeaderText = "Batch File";
                dgvDataApproved.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDataApproved.Columns[1].HeaderText = "File Name";
                dgvDataApproved.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dgvDataApproved.Columns[2].HeaderText = "Total Record";
                dgvDataApproved.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                dgvDataApproved.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDataApproved.Columns[3].HeaderText = "Uploaded Date";
                dgvDataApproved.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDataApproved.Columns[4].Visible = false;
                dgvDataApproved.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDataApproved.Columns[5].HeaderText = "Sent Mail";
                dgvDataApproved.Columns[5].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                var dgvCellStyle = new DataGridViewCellStyle();
                dgvCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dgvDataApproved.Columns[5].DefaultCellStyle = dgvCellStyle;
            }
            catch (Exception ex) { throw ex; }

        }

        private void loadDataPending()
        {
            try
            {
                BatchFileUploadBLL batchFileUploadBll = new BatchFileUploadBLL();
                DataTable dtResult = batchFileUploadBll.GetBatchFileByStatus(Constant.PENDING);
                dgvDataPending.DataSource = null;
                dgvDataPending.Columns.Clear();
                dgvDataPending.DataSource = dtResult;
                this.dgvDataPending.Sort(this.dgvDataPending.Columns[3], ListSortDirection.Descending);
                dgvDataPending.Columns[0].HeaderText = "Batch File";
                dgvDataPending.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDataPending.Columns[1].HeaderText = "File Name";
                dgvDataPending.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dgvDataPending.Columns[2].HeaderText = "Total Record";
                dgvDataPending.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                dgvDataPending.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDataPending.Columns[3].HeaderText = "Uploaded Date";
                dgvDataPending.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDataPending.Columns[4].Visible = false;
                dgvDataPending.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            }
            catch (Exception ex) { throw ex; }
        }

        private void dgvDataApproved_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                int selectedRowCount = dgvDataApproved.Rows.GetRowCount(DataGridViewElementStates.Selected);
                if (selectedRowCount > 0)
                {
                    DataRow dr = ((DataRowView)dgvDataApproved.SelectedRows[0].DataBoundItem).Row;
                    frmDataUpload frmDateUpload = new frmDataUpload(dr[0].ToString());
                    frmDateUpload.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void dgvDataPending_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                int selectedRowCount = dgvDataPending.Rows.GetRowCount(DataGridViewElementStates.Selected);
                if (selectedRowCount > 0)
                {
                    DataRow dr = ((DataRowView)dgvDataPending.SelectedRows[0].DataBoundItem).Row;
                    frmDataUpload frmDateUpload = new frmDataUpload(dr[0].ToString());
                    frmDateUpload.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void UpdateApproved4Dashboard()
        {
            try
            {
                DataTable dtNumber = new DataTable();
                BatchFileUploadBLL batchFileUploadBll = new BatchFileUploadBLL();
                DataTable dtResult = batchFileUploadBll.GetBatchFileByStatus(Constant.APPROVED);

                for (int i = 0; i < dtResult.Rows.Count; i++)
                {
                    CandidateBLL candidateBll = new CandidateBLL();
                    DataTable dt = candidateBll.GetByBatchFileID(dtResult.Rows[i][0].ToString());

                    dtNumber.Merge(dt);
                }

                //08Jan2015 Update number of Approved Candidate
                buttonX2.Text = "APPROVED" + Environment.NewLine + dtNumber.Rows.Count.ToString();
                labelX2.Text = "Total Approved:" + dtNumber.Rows.Count.ToString();
            }
            catch (Exception ex) { throw ex; }
        }

        private void UpdatePending4Dashboard()
        {
            try
            {
                DataTable dtNumber = new DataTable();
                BatchFileUploadBLL batchFileUploadBll = new BatchFileUploadBLL();
                DataTable dtResult = batchFileUploadBll.GetBatchFileByStatus(Constant.PENDING);

                for (int i = 0; i < dtResult.Rows.Count; i++)
                {
                    CandidateBLL candidateBll = new CandidateBLL();
                    DataTable dt = candidateBll.GetByBatchFileID(dtResult.Rows[i][0].ToString());

                    dtNumber.Merge(dt);
                }

                //08Jan2015 Update number of Pending Canadidate
                buttonX3.Text = "PENDING" + Environment.NewLine + dtNumber.Rows.Count.ToString();
                labelX3.Text = "Total Pending: " + dtNumber.Rows.Count.ToString();
            }
            catch (Exception ex) { throw ex; }
        }

        private void UpdateReadyToApprove4Dashboard()
        {
            try
            {
                DataTable dtNumber = new DataTable();
                string status = "";
                if (!isApprove)
                {
                    status = Constant.NEED_TO_VERIFY;
                }
                else
                {
                    status = Constant.NEED_TO_APPROVE;
                }

                BatchFileUploadBLL batchFileUploadBll = new BatchFileUploadBLL();
                DataTable dtResult = batchFileUploadBll.GetBatchFileByStatus(status);

                for (int i = 0; i < dtResult.Rows.Count; i++)
                {
                    CandidateBLL candidateBll = new CandidateBLL();
                    DataTable dt = candidateBll.GetByBatchFileID(dtResult.Rows[i][0].ToString());
                    dtNumber.Merge(dt);
                }

                labelX4.Text = "Total Ready To Approve: " + dtNumber.Rows.Count;
                buttonX4.Text = "READY TO APPROVE" + Environment.NewLine + dtNumber.Rows.Count;
            }
            catch (Exception ex) { throw ex; }
        }

        private void tabItem4_Click(object sender, EventArgs e)
        {
            try
            {
                UpdatePending4Dashboard();
                UpdateApproved4Dashboard();
                UpdateReadyToApprove4Dashboard();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        /// <summary>
        /// Click right mouse button to send employee excel file to Admin Central
        /// </summary>
        List<int> selectedBatchFileId;
        List<int> selectedSentBatchFileId;
        private void dgvDataApproved_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Right)
                {
                    DataGridViewSelectedRowCollection selectedRowClt = dgvDataApproved.SelectedRows;
                    selectedBatchFileId = new List<int>();
                    selectedSentBatchFileId = new List<int>();
                    foreach (DataGridViewRow row in selectedRowClt)
                    {
                        if (row.Cells[5].Value.Equals("No"))
                        {
                            selectedBatchFileId.Add(int.Parse(row.Cells[0].Value.ToString()));
                        }
                        if (row.Cells[5].Value.Equals("Yes"))
                        {
                            selectedSentBatchFileId.Add(int.Parse(row.Cells[0].Value.ToString()));
                        }
                    }
                    dgvDataApproved.ContextMenuStrip = ctmsSendMail;
                    ctmsSendMail.Show(Cursor.Position);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }


        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                List<string> fileTempList = new List<string>();
                int count = 0;
                foreach (int batchFileID in selectedBatchFileId)
                {
                    count++;
                    DataTable employmentInforByBatchFile = new SaleInfoBLL().BuildEmploymentInformation(batchFileID.ToString());
                    string fileName = "Employment_" + DateTime.Now.ToString("ddMMyyyy") + string.Format(" ({0})", count) + ".xls";
                    string fileTemp = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + fileName;
                    NPOIHelper.ExportSaleInfoToEmploymentInfo(employmentInforByBatchFile, "EMPLOYMENT", fileTemp, Employment_SaleInfoFieldMappingDict());
                    fileTempList.Add(fileTemp);
                }
                if (dgvDataApproved.SelectedRows.Count - count > 0)
                {
                    DialogResult result = MessageBox.Show("Some files were already sent. Do you want to send it one more time?", "Sent files", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == System.Windows.Forms.DialogResult.Yes)
                    {
                        foreach (int batchFileID in selectedSentBatchFileId)
                        {
                            count++;
                            DataTable employmentInforByBatchFile = new SaleInfoBLL().BuildEmploymentInformation(batchFileID.ToString());
                            string fileName = "Employment_" + DateTime.Now.ToString("ddMMyyyy") + string.Format(" ({0})", count) + ".xls";
                            string fileTemp = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + fileName;
                            NPOIHelper.ExportSaleInfoToEmploymentInfo(employmentInforByBatchFile, "EMPLOYMENT", fileTemp, Employment_SaleInfoFieldMappingDict());
                            fileTempList.Add(fileTemp);
                        }
                    }
                }
                //Send mail
                SendEMailThroughOUTLOOK(fileTempList);
                count = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void SendEMailThroughOUTLOOK(List<string> fileTempList)
        {
            try
            {
                // Create the Outlook application.
                Microsoft.Office.Interop.Outlook.Application oApp = new Outlook.Application();

                // Create a new mail item.
                Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

                // Set HTMLBody. 
                //add the body of the email
                oMsg.HTMLBody = "Content";

                //Add an attachment.
                String sDisplayName = "MyAttachment";
                int iPosition = (int)oMsg.Body.Length + 1;
                int iAttachType = (int)Outlook.OlAttachmentType.olByValue;

                //now attached the file             

                foreach (string fileTemp in fileTempList)
                {
                    var oAttach = oMsg.Attachments.Add(fileTemp, iAttachType, iPosition, sDisplayName);
                    if (File.Exists(fileTemp)) File.Delete(fileTemp);
                }



                //Subject line
                oMsg.Subject = "Employment_" + DateTime.Now.ToString("ddMMyyyy") + " " + fileTempList.Count + " file(s)";
                oMsg.To = "";
                oMsg.CC = "";
                oMsg.Display(true);

                foreach (int batchFileID in selectedBatchFileId)
                {
                    new BatchFileUploadBLL().SetMailSent(batchFileID.ToString());
                }
                fileTempList.Clear();
                loadDataApproved();

            }

            catch (Exception ex)
            {
                MessageBox.Show("Error with sending proccess");
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }


        public Dictionary<string, string> Employment_SaleInfoFieldMappingDict()
        {
            try
            {
                Dictionary<string, string> employment_FieldLabelDict = new Dictionary<string, string>();
                employment_FieldLabelDict.Add("ProfileID", "Profile ID");
                employment_FieldLabelDict.Add("SaleCode", "Current Sales Code");
                employment_FieldLabelDict.Add("CVCode", "Candidate Code");
                employment_FieldLabelDict.Add("EmployeeFullName", "Employee Full Name");
                employment_FieldLabelDict.Add("EmployeeFullNameE", "Employee Full Name_E");
                employment_FieldLabelDict.Add("Role", "Role");
                employment_FieldLabelDict.Add("Level", "Level");
                employment_FieldLabelDict.Add("Category", "Category");
                employment_FieldLabelDict.Add("ProductCategory", "Product Category");
                employment_FieldLabelDict.Add("Product", "Product");
                employment_FieldLabelDict.Add("TeamName", "Team Name");
                employment_FieldLabelDict.Add("TeamLeaderCode", "Team Leader Code");
                employment_FieldLabelDict.Add("Channel", "Channel");
                employment_FieldLabelDict.Add("JoiningDate", "Joining Date");
                employment_FieldLabelDict.Add("PromotionTransferDate", "Promotion/Role Transfer Date");
                employment_FieldLabelDict.Add("Status", "Status");
                employment_FieldLabelDict.Add("ContractType", "Contract Type");
                employment_FieldLabelDict.Add("ContractTerm", "Contract Term");
                employment_FieldLabelDict.Add("ContractorName", "Contractor Name");
                employment_FieldLabelDict.Add("ContractSignDate", "Contract Sign Date");
                employment_FieldLabelDict.Add("ContractExpiryDate", "Contract Expiry Date");
                employment_FieldLabelDict.Add("BatchFileID", "Batch File ID");
                return employment_FieldLabelDict;
            }
            catch (Exception ex) { throw ex; }
        }

        private void dgvDataApproved_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvDataApproved.Columns[e.ColumnIndex].HeaderText.Equals("Sent Mail"))
            {
                if (dgvDataApproved.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.Equals("No"))
                {
                    DialogResult result = MessageBox.Show("Do you want to send this file?", "Send mail", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        string batchFileID = dgvDataApproved.Rows[e.RowIndex].Cells[0].Value.ToString();
                        DataTable employmentInforByBatchFile = new SaleInfoBLL().BuildEmploymentInformation(batchFileID.ToString());
                        selectedBatchFileId = new List<int>();
                        selectedBatchFileId.Add(int.Parse(batchFileID));
                        string fileName = "Employment_" + DateTime.Now.ToString("ddMMyyyy") + ".xls";
                        string fileTemp = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + fileName;
                        NPOIHelper.ExportSaleInfoToEmploymentInfo(employmentInforByBatchFile, "EMPLOYMENT", fileTemp, Employment_SaleInfoFieldMappingDict());
                        //Send mail
                        List<string> fileTempList = new List<string>();
                        fileTempList.Add(fileTemp);
                        SendEMailThroughOUTLOOK(fileTempList);
                    }
                }
            }
        }

        private void dgvDataApproved_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            foreach (DataGridViewRow row in dgvDataApproved.Rows)
            {
                if (row.Cells[5].Value.Equals("No"))
                {
                    row.Cells[5] = new DataGridViewLinkCell();
                }

            }
        }

        private void txtBatchFile_TextChanged(object sender, EventArgs e)
        {
            if (System.Text.RegularExpressions.Regex.IsMatch(txtBatchFile.Text, "[^0-9]"))
            {
                //MessageBox.Show("Please enter only numbers.");
                txtBatchFile.Undo();
                txtBatchFile.ClearUndo();
            }
            else
            {
                txtBatchFile.ClearUndo();
            }
        }
    }
}
